import axios from 'axios';
import { Message } from 'element-ui';
// import { getToken } from '@/utils/auth';
import {apiBaseUrl} from '../../config';
// import router from '../../router';
// import {removeToken} from '../../utils/auth';
import {trimString} from "../../utils";

// create an axios instance
const service = axios.create({
  baseURL: apiBaseUrl, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    'Content-Type': 'application/json',
    'Pre-ComId': null
  },
  timeout: 10000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    let comId = localStorage.getItem('comId');

    // do something before request is sent
    // if (getToken()) {
    if(true) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['Authorization'] = getToken();
      // config.headers['Pre-ComId'] = comId;
    }
    let contentType = config.headers['Content-Type'];
    if (contentType.indexOf('application/json') > -1) {
      config.data = dealData(config.data);
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // IE 8-9
    if (response.data == null && response.config.responseType === 'json' && response.request.responseText != null) {
      try {
        // eslint-disable-next-line no-param-reassign
        response.data = JSON.parse(response.request.responseText);
      } catch (e) {
        // ignored
      }
    }
    const res = response.data;
    if (res.code === -2) {
      Message({
        message: '登录已失效，请重新登录',
        type: 'warning',
        duration: 3 * 1000
      });
      // removeToken();
      // router.push({path: '/login'});
    } else if (res.code !== 0) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      });
      return Promise.reject(new Error(res.msg || 'Error'));
    } else {
      return res;
    }
  },
  error => {
    console.log('err' + error); // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

function dealData(data) {
  if(data === undefined || !data) {
    return data;
  }
  try{
    let json = JSON.parse(data);
    for (let i in json) {
      json[i] = trimString(json[i]);
    }
    return JSON.stringify(json);
  }catch (e) {
    return data;
  }
}

export default service;
